package com.lanou3g.ptp.api.advice;

import com.lanou3g.ptp.exception.PermissionDeniedException;
import com.lanou3g.ptp.exception.PtpException;
import com.lanou3g.ptp.api.web.controller.BaseController;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 创建人: 武奇
 * 创建事件: 2019/7/30
 */
@RestControllerAdvice(basePackageClasses = BaseController.class)
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(PermissionDeniedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public PtpResult resolveSsoException(PermissionDeniedException ex) {
        log.info("处理授权异常", ex);
        return PtpResultUtils.error(401, ex.getMessage());
    }

    @ExceptionHandler(PtpException.class)
    public ResponseEntity<PtpResult> resolvePtpException(PtpException ex) {
        log.debug("处理PtpException", ex);
        int code = ex.getCode() == 0 ? 500 : ex.getCode();
        return ResponseEntity.status(code).body(PtpResultUtils.error(code, ex.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public PtpResult resolveAllException(Exception ex) {
        log.error("处理全局异常");
        ex.printStackTrace();
        return PtpResultUtils.error(500, "后台出异常了, 找姚云鹏: " + ex.getMessage());
    }

}
